//
//  UIImage+Extension.swift
//  新浪微博
//
//  Created by 胡不归是大虾 on 2016/10/8.
//  Copyright © 2016年 胡不归是大虾. All rights reserved.
//

import UIKit
extension UIImage {
    //截取屏幕
    class func screenShot () -> UIImage{
        //拿到当前窗口
        let window = UIApplication.shared.keyWindow!
        //开启上下文
        UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, UIScreen.main.scale)
        //将当前屏幕绘制进上下文
        window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
        //从上下文中取出图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        //返回图片
        return image!
    }
    //等比例压缩图片的方法
    func scaleImage(width:CGFloat)->UIImage{
        let imageW = self.size.width
        let imageH = self.size.height
        //如果图片的宽度小于压缩的宽度就直接返回
        if imageW < width{
            return self
        }
        //计算高度
        let scaleH = imageH / imageW * width
        //开启图像上下文
        UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: scaleH), false, UIScreen.main.scale)
        //将图像绘制进上下文
        self.draw(in: CGRect(x: 0, y: 0, width: width, height: scaleH))
        //获取图片
        let scaleImage = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        return scaleImage!
    }

}
